import React, { Component } from "react";
import { DeleteOutlined, EditOutlined, PlusCircleOutlined, StopOutlined, KeyOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, message, Divider, Tag, Modal, Input } from "antd";
import { getUsers, deleteUser, freezeUser, modifyUserPassword } from "@/api/user";
import TableComponent from '@/components/TableList';
import SearchHeader from '@/components/SearchHeader';
import EditForm from "./components/edit"
import { getImage} from '@/utils/renderCell'
import { widgetProps } from '@/utils/constant';
class User extends Component {
  tableRef = React.createRef();
  state = {
    list: [],
    editModalVisible: false, // 编辑新增 显示控制
    currentRowData: {},
    listQuery: {},
    password: '',
    editMode: false // 添加 编辑模式
  };

  // 表格数据更新 抛出数据
  handleGetData = data => {
    this.setState({
      list: data.list
    })
  }
  // 处理搜索
  handleSearch = (listQuery) => {
    this.setState({
      listQuery
    });
  };

  handleChangePasswordInput = e => {
    this.setState({
      password: e.target.value
    });
  };


  handleDeleteUser = (row) => {
    deleteUser({ id: row.userId }).then(res => {
      message.success("删除成功")
      this.tableRef.current.fetchData();
    })
  }

  handleDisableUser = (row) => {
    
    Modal.confirm({
      title: "更改用户状态",
      content: "启用/冻结 用户（用户冻结后，用户无法登陆）",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        freezeUser({ id: row.userId, status: Math.abs(row.status - 1)}).then(res => {
          message.success("设置成功")
          this.tableRef.current.fetchData();
        })
      }
    })
  }


  handleEditPassword = row => {
    Modal.confirm({
      title: '请输入用户新密码',
      icon: <ExclamationCircleOutlined />,
      content: <Input  allowClear  onChange={this.handleChangePasswordInput}/>,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        modifyUserPassword({
          id: row.userId,
          password: this.state.password
        }).then(() => {
          message.success('密码修改成功');
        })
      },
      onCancel: () => {
        this.setState({
          password: ''
        })
      }
    });
  };

  hadnleAditAddOkHandler = (values, form) => {
    this.tableRef.current.fetchData();
    this.setState({
      editUserModalVisible: false,
    });
  };

  // 取消操作 关闭抽屉
  handleCancel = _ => {
    this.setState({
      editUserModalVisible: false,
    });
  };


  handleAddUser = (row) => {
    this.setState({
      editUserModalVisible: true,
      editMode: false
    });
  };

  handleEditUser = (row) => {
    const currentRowData = this.state.list.find(v => v.userId === row.userId)
    this.setState({
      currentRowData,
      editUserModalVisible: true,
      editMode: true
    });
  };

  // 头部搜索配置
  meta = {
    fields: [
      {
        key: 'identifier',
        label: '用户名称',
        widgetProps
      },
      {
        key: 'nickName',
        label: '用户昵称',
        widgetProps
      },
      {
        key: 'realName',
        label: '真实名称',
        widgetProps
      },
      {
				key: 'status',
				label: '用户状态',
				widget: 'select',
        widgetProps,
				options: [
					{
						label: '可用',
						value: 0
					},
					{
						label: '禁用',
						value: 1
					}
				]
			}
    ],
  };

  // 表格列 字段定义
  columns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: getImage
    },

    {
      title: '用户状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        // 0-正常 1-禁用 2-注销
        let color = "", text = "";
        switch (status) {
          case 1:
            text = "禁用";
            color = "#b74725"; //红色
            break;
          case 2:
            text = "注销";
            color = "#c3bfbe"; //灰色
            break;
          default:
            text = "正常";
            color = '#25b752';
            break;
        }
        return (
          <Tag color={color} key={status}>
            {text}
          </Tag>
        );
      }
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      key: 'registerTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, row) => (
        <>
          <Button type="primary" shape="circle" icon={<EditOutlined />} title="编辑用户" onClick={this.handleEditUser.bind(null, row)} />
          <Divider type="vertical" />
          <Button type="primary" shape="circle" icon={<DeleteOutlined />} title="删除用户" onClick={this.handleDeleteUser.bind(null, row)} />
          <Divider type="vertical" />
          <Button type="primary" shape="circle" icon={<StopOutlined />} title="启用/冻结" onClick={this.handleDisableUser.bind(null, row)} ></Button>
          <Divider type="vertical" />
          <Button type="primary" shape="circle" icon={<KeyOutlined />} title="修改密码" onClick={this.handleEditPassword.bind(null, row)} ></Button>
        </>
      )
    }

  ];
  render() {

    return (
      <>
        <SearchHeader onSearch={this.handleSearch} meta={this.meta}>
          <Button type='primary' onClick={this.handleAddUser} icon={<PlusCircleOutlined />}>新增用户</Button>
        </SearchHeader>
        <br />
        <TableComponent idName='userId' getTableListApi={getUsers} columns={this.columns} queryParams={this.state.listQuery} ref={this.tableRef} onGetData={this.handleGetData}/>
        <EditForm
          title={this.state.editMode ? '编辑用户' : '新增用户'}
          editMode={this.state.editMode}
          currentRowData={this.state.currentRowData}
          visible={this.state.editUserModalVisible}
          onCancel={this.handleCancel}
          onOk={this.hadnleAditAddOkHandler}
        />
      </>
    );
  }
}

export default User;
